package com.grm.data;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 实现整数的数字反转
 * <p>
 * 给出32位的有符号整数，将这个整数每位上的数字进行反转
 * 1. 123 -> 321
 * 2. -123 -> -321
 * 3. 120 -> 21
 * 4. 溢出返回0
 *
 * @author gaorimao
 * @since 2022-09-24
 */
public class J001TwoSum {
    public static void main(String[] args) {
        int[] array = {3, 3};
        int[] result = twoSumV2(array, 6);
        System.out.println("result = " + Arrays.toString(result));
    }

    // 暴力解法
    public static int[] twoSum(int[] nums, int target) {
        int left = 0;
        int right = left + 1;
        while (left < right) {
            for (right = left + 1; right <= nums.length - 1; right++) {
                if (nums[left] + nums[right] == target) {
                    return new int[]{left, right};
                }
            }
            left++;
        }
        return new int[]{};
    }

    // 存为map
    public static int[] twoSumV2(int[] nums, int target) {
        // key = 值, value = 索引
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int otherVal = target - nums[i];
            if (map.containsKey(otherVal)) {
                return new int[]{map.get(otherVal), i};
            }
            map.put(nums[i], i);
        }
        return new int[]{};
    }
}
